package com.haitaoit.chengquan.module.center.activity.xuqiu;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.module.center.adapter.xuqiu.MyXuqiuDetailAdapter;
import com.haitaoit.chengquan.module.center.model.MyXuqiuDetailModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.CircleImageView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.QRatingBar;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyXuqiuEndDetailActivity extends BaseActivity {
    @ViewInject(R.id.to_me_evaLL)
    LinearLayout to_me_evaLL;
    @ViewInject(R.id.xuqiu_state)
    TextView xuqiu_state;
    @ViewInject(R.id.xuqiu_end_detail_money)
    TextView xuqiu_end_detail_money;
    @ViewInject(R.id.end_detail_baojia_money)
    TextView end_detail_baojia_money;
    @ViewInject(R.id.end_detail_finish)
    TextView end_detail_finish;
    @ViewInject(R.id.end_detail_eva)
    TextView end_detail_eva;
    @ViewInject(R.id.title_img)
    ImageView title_img;
    @ViewInject(R.id.demand_number)
    TextView demand_number;
    @ViewInject(R.id.detail_title)
    TextView detail_title;
    @ViewInject(R.id.detail_type)
    TextView detail_type;
    @ViewInject(R.id.head_portrait)
    CircleImageView head_portrait;
    @ViewInject(R.id.real_name)
    TextView real_name;
    @ViewInject(R.id.addtime)
    TextView addtime;
    @ViewInject(R.id.contact)
    TextView contact;
    @ViewInject(R.id.contact_position)
    TextView contact_position;
    @ViewInject(R.id.contact_information)
    TextView contact_information;
    @ViewInject(R.id.remarks)
    TextView remarks;
    @ViewInject(R.id.xuqiu_detail_LL)
    LinearLayout xuqiu_detail_LL;
    @ViewInject(R.id.eva_head_portrait)
    CircleImageView eva_head_portrait;
    @ViewInject(R.id.eva_name)
    TextView eva_name;
    @ViewInject(R.id.eva_content)
    TextView eva_content;
    @ViewInject(R.id.eva_addtime)
    TextView eva_addtime;
    @ViewInject(R.id.eva_star)
    QRatingBar eva_star;
    @ViewInject(R.id.xuqiu_map)
    TextView xuqiu_map;
    @ViewInject(R.id.scrollview_listview2)
    MyListView listView;
    @ViewInject(R.id.null_information_layout)
    LinearLayout null_information_layout;
    @ViewInject(R.id.detail_LL2)
    LinearLayout detail_LL2;


    private String id;
    private MyXuqiuDetailModel model;
    private MyXuqiuDetailAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_my_xuqiu_end_detail);
        ExitApplication.getInstance().addActivity(this);
        setTitle_V("订单详情");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        adapter = new MyXuqiuDetailAdapter(this);
        adapter.setBackCall(backCall);
        id = getIntent().getStringExtra("order_id");
    }

    @Override
    protected void onResume() {
        httpGetuser_demand_model();
        super.onResume();
    }

    @OnClick({R.id.xuqiu_map, R.id.contact_information, R.id.end_detail_finish, R.id.end_detail_eva,})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.xuqiu_map:
                intent.setClass(this, MyXuqiuMapActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
                break;
            case R.id.contact_information:// 联系方式
                Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +
                        model.getDemand_offer_model().getContact_information()));
                startActivity(in);
                break;
            case R.id.end_detail_finish:// 服务完成
                Dialog dlg = DialogUtil.showInfoDialog1(this, "提示", "您确定该需求服务已完成吗？", "确定", "还没有", new BackCall() {
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.confirm:// 确定
                                httpGetdemand_complete_order(model.getOrder_no());
                                break;
                        }
                        super.deal(which);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();
                break;
            case R.id.end_detail_eva:// 评价服务商
                intent.setClass(this, XuqiuEvaluateActivity.class);
                intent.putExtra("demand_id", model.getId());
                intent.putExtra("type", "1");
                startActivity(intent);
                break;
        }
        super.onClick(v);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            final int position = (Integer) obj[0];
            Intent intent = new Intent();
            switch (which) {
                case R.id.xuqiu_detail_lookinfo:// 查看详情
                    intent.setClass(MyXuqiuEndDetailActivity.this, MyXuqiuBaojiaActivity.class);
                    intent.putExtra("id", model.getDemand_offer_list().get(position).getId());
                    startActivity(intent);
                    break;
                case R.id.xuqiu_detail_choose:// 选他服务
                    // order_type 未报价 已报价
                    if (model.getOrder_status().equals("1")) {
                        Dialog dlg = DialogUtil.showInfoDialog2(MyXuqiuEndDetailActivity.this,
                                "当前报价还未结束，报价时间内你还不能选择服务商服务，请耐心等待报价结束再选择服务商服务", "", "知道了", new BackCall() {
                                    public void deal(int which, Object... obj) {
                                        switch (which) {
                                        }
                                        super.deal(which);
                                    }
                                });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();
                    } else if (model.getOrder_status().equals("2")) {
                        Dialog dlg = DialogUtil.showInfoDialog2(MyXuqiuEndDetailActivity.this,
                                "选定该服务商则需要支付¥" + model.getDemand_offer_list().get(position).getOffer_money()
                                        + "到他的账号完成服务商选择", "再想想", "去支付", new BackCall() {
                                    public void deal(int which, Object... obj) {
                                        switch (which) {
                                            case R.id.cancel:// 确定
                                                Intent intent = new Intent(MyXuqiuEndDetailActivity.this, PaymentActivity.class);
                                                intent.putExtra("type", "1");
                                                intent.putExtra("order_no", model.getDemand_offer_list().get(position).getOrder_no());
                                                intent.putExtra("order_amount", model.getDemand_offer_list().get(position).getOffer_money());
                                                startActivity(intent);
                                                break;
                                        }
                                        super.deal(which);
                                    }
                                });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();
                    }
                    break;
            }
            super.deal(which, obj);
        }
    };

    // 详情
    private void httpGetuser_demand_model() {
        final List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_demand_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            model = gson.fromJson(Response, MyXuqiuDetailModel.class);
                            xuqiu_detail_LL.setVisibility(View.VISIBLE);
                            detail_LL2.setVisibility(View.GONE);
                            xuqiu_map.setVisibility(View.GONE);
                            if (model.getOrder_status().equals("1")) {
                                xuqiu_state.setText("未报价");
                                if (model.getOrder_type().equals("1")) {
                                    if (model.getDemand_offer_list() == null || model.getDemand_offer_list().size() == 0) {
                                        null_information_layout.setVisibility(View.VISIBLE);
                                        listView.setVisibility(View.GONE);
                                    } else {
                                        adapter.setList(model.getDemand_offer_list());
                                        adapter.setType(model.getOrder_status());
                                        listView.setAdapter(adapter);
                                    }
                                }
                                xuqiu_detail_LL.setVisibility(View.GONE);
                            } else if (model.getOrder_status().equals("2")) {
                                xuqiu_map.setVisibility(View.VISIBLE);
                                xuqiu_state.setText("已报价");
                                if (model.getOrder_type().equals("1")) {
                                    if (model.getDemand_offer_list() == null || model.getDemand_offer_list().size() == 0) {
                                        null_information_layout.setVisibility(View.VISIBLE);
                                        listView.setVisibility(View.GONE);
                                    } else {
                                        adapter.setList(model.getDemand_offer_list());
                                        adapter.setType(model.getOrder_status());
                                        listView.setAdapter(adapter);
                                    }
                                }
                                xuqiu_detail_LL.setVisibility(View.GONE);
                            } else if (model.getOrder_status().equals("3")) {
                                xuqiu_state.setText("已支付");
                                if (model.getIs_service().equals("1")) {
                                    xuqiu_detail_LL.setVisibility(View.GONE);
                                } else {
                                    xuqiu_detail_LL.setVisibility(View.VISIBLE);
                                    end_detail_eva.setVisibility(View.GONE);
                                }
                                to_me_evaLL.setVisibility(View.GONE);
                                detail_LL2.setVisibility(View.VISIBLE);
                                put();
                            } else if (model.getOrder_status().equals("4")) {
                                xuqiu_state.setText("已完成");
                                to_me_evaLL.setVisibility(View.VISIBLE);
                                end_detail_finish.setVisibility(View.GONE);

                                if (model.getOrder_type().equals("2")) {
                                    to_me_evaLL.setVisibility(View.GONE);
                                } else if (model.getOrder_type().equals("3")) {
                                    to_me_evaLL.setVisibility(View.VISIBLE);

                                    //取评价值
                                    ImageLoader.getInstance().displayImage(model.getDemand_evaluation_model().getHead_portrait(), eva_head_portrait);
                                    eva_name.setText(model.getDemand_evaluation_model().getName());
                                    eva_content.setText(model.getDemand_evaluation_model().getContent());
                                    eva_addtime.setText(model.getDemand_evaluation_model().getAddtime());
                                    eva_star.setRating(Float.parseFloat(model.getDemand_evaluation_model().getScore()));
                                }

                                // 需求商是否评价1否2是(否的话就显示评价)
                                if (model.getIs_evaluation().equals("1")) {
                                    xuqiu_detail_LL.setVisibility(View.VISIBLE);
                                    end_detail_finish.setVisibility(View.GONE);
                                } else {
                                    xuqiu_detail_LL.setVisibility(View.GONE);
                                }
                                detail_LL2.setVisibility(View.VISIBLE);
                                put();
                            }

                            demand_number.setText("需求编号：" + model.getDemand_number());
                            ImageLoader.getInstance().displayImage(model.getTitle_img(), title_img);
                            detail_title.setText(model.getTitle());
                            detail_type.setText("分类：" + model.getType());
                            SpannableString msp = new SpannableString("参考价格：¥ " + model.getReference_price());
                            msp.setSpan(new ForegroundColorSpan(Color.RED), 5, ("参考价格：¥ " + model.getReference_price()).length(),
                                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            msp.setSpan(new RelativeSizeSpan(1.5f), 6, ("参考价格：¥ " + model.getReference_price()).length(),
                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            xuqiu_end_detail_money.setText(msp);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public void put() {
        ImageLoader.getInstance().displayImage(model.getDemand_offer_model().getHead_portrait(), head_portrait);
        real_name.setText(model.getDemand_offer_model().getReal_name());
        addtime.setText("报价时间：" + model.getDemand_offer_model().getAddtime());
        SpannableString msp1 = new SpannableString("¥ " + model.getDemand_offer_model().getOffer_money());
        msp1.setSpan(new RelativeSizeSpan(1.5f), 1, ("¥ " + model.getDemand_offer_model().getOffer_money()).length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        end_detail_baojia_money.setText(msp1);
        contact.setText(model.getDemand_offer_model().getContact());
        contact_position.setText(model.getDemand_offer_model().getContact_position());
        contact_information.setText(model.getDemand_offer_model().getContact_information());
        if (model.getDemand_offer_model().getRemarks().equals(""))
            remarks.setText("无");
        else
            remarks.setText(model.getDemand_offer_model().getRemarks());
    }

    // 需求服务完成订单
    private void httpGetdemand_complete_order(String order_no) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdemand_complete_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            httpGetuser_demand_model();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }
}
